package com.erclab.xpresso
{

	import com.erclab.xpresso.reports.Report;
	import com.erclab.xpresso.util.UIUtil;
	
	import mx.rpc.http.mxml.HTTPService;	
	import mx.collections.ArrayCollection;
	import mx.controls.dataGridClasses.DataGridColumn;
	import mx.core.UIComponent;
	import mx.controls.DataGrid;
	
	import flash.display.DisplayObject;
	
	
	public class ReportManager
	{
		public var theReport:Report;
		public var columnsArray:Array;
		
		public function ReportManager(reportName:String):void{
			theReport = new Report(reportName);
		}
		
		public function deleteSelectedObject(deleteService:HTTPService, 
												object:Object):void{
			var params:Object = new Object();
			params.reportAction = "Delete";
			params.reportName = theReport.reportName;
			params.element = object[theReport.uniqueKeyName];
			params.uniqueKeyValue = object.uniqueKeyValue;
			deleteService.send(params);
		}
		
		public function setupData(mainService:HTTPService, 
									attachingElement:DataGrid):void{
			theReport.uniqueKeyName = mainService.lastResult.report.uniqueKeyName;
			
			var theData:ArrayCollection = mainService.lastResult.report.record as ArrayCollection;
			theReport.theData = theData;
			theReport.theGrid = attachingElement;
						
			var columns:ArrayCollection = mainService.lastResult.report.column as ArrayCollection;
			columnsArray = new Array();

			var i:int = 0;
			for each ( var element:Object in columns) {
				
				/* Not necessary for now, maybe later 
				initElements();
				
				var ClassReference:Class = getDefinitionByName(element.dataType) as Class;
	            var instance:DisplayObject = new ClassReference();
	            var parameters:Object = element.parameters as Object;
				for (var p:String in element.parameters){
					instance[p] = element.parameters[p];
				}
				instance.name = element.id;
				
	            dynamicElements.addItem(instance);
	            if (attachingElement != null) {
		            attachingElement.addChild(UIComponent(instance));
		            var fe:FormElement = FormElement(instance);
		            fe.createLabel(attachingElement, element.label);
		            fe.setAttribute("destinationColumn", element.DestinationColumn);
	            }*/
	            
				var column:DataGridColumn = new DataGridColumn();
				column.dataField = element.ColumnName;
				column.headerText = element.HeaderText;
				if (element.Parameters != null && element.Parameters != "null"){
					var parameters:Object = element.Parameters as Object;
					for (var p:String in element.Parameters){
						column[p] = element.Parameters[p];
					}	
				}				
				columnsArray[i] = column;
				i++;
			}
			attachingElement.columns = columnsArray;
			attachingElement.dataProvider = mainService.lastResult.report.record;
		}
		
		
	}
}